import request from './http'
import store from "../store";


// 封装工具函数
let utils = {

  // 获取时间日期,day为获取多少天以后的值，默认为0表示今天
  getNow(type = 1, day = 0) {
    var DateObj = new Date();
    var nowTimeStem = DateObj.getTime();
    var endTimeStem = nowTimeStem + 24 * 60 * 60 * 1000 * day;
    var date = new Date(endTimeStem);
    switch (type) {
      // 纯日期模式
      case 1:
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
        break;
        // 日期时间模式
      case 2:
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
        break;
        // 纯时间模式
      case 3:
        return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
        break;
    }
  },


  /**
   * 是否为json对象
   * @param {*} obj 
   */
  isJsonObj(obj) {
    var isjson = typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    return isjson;
  },

  /***
   * @方法名: setPhone
   * @注释: 电话号码脱敏处理（157 **** 3572）
   * @param {*} num 电话号
   * @param {*} start 开始截取位置
   * @param {*} length 截取长度
   * @returns {number}
   */
  setPhone(num, start = 3, length = 4) {
    let newNum = num + "";
    return newNum.slice(0, start) + "*".repeat(length) + newNum.slice(newNum.length - start - 1);
  },

  /***
   * @方法名: backHome
   * @注释: 返回上一页（页面栈中大于2个返回上一页小于两个返回index首页）
   */
  backHome() {
    // #ifdef MP-WEIXIN
    uni.navigateBack({
      delta: 1,
      fail() {
        uni.reLaunch({
          url: "/pages/index/index",
        });
      },
    });
    // #endif
    // #ifdef H5
    history.back()
    // #endif
  },

  // 数组去重合并
  mergeArray(arr1, arr2) {
    var _arr = new Array();
    for (var i = 0; i < arr1.length; i++) {
      _arr.push(arr1[i]);
    }
    for (var i = 0; i < arr2.length; i++) {
      var flag = true;
      for (var j = 0; j < arr1.length; j++) {
        if (arr2[i] == arr1[j]) {
          flag = false;
          break;
        }
      }
      if (flag) {
        _arr.push(arr2[i]);
      }
    }
    return _arr;
  },

  // 获取数据类型
  getType(data) {
    let type = typeof data;
    if (type !== "object") {
      return type
    }
    return Object.prototype.toString.call(data).replace(/^\[object (\S+)\]$/, '$1')
  },

  /***
   * 获取当前周几
   * @returns {string}
   */
  getWeekDate() {
    var now = new Date();
    var day = now.getDay();
    var weeks = new Array("7", "1", "2", "3", "4", "5", "6");
    var week = weeks[day];
    return week;
  },
  /***
   * 日期格式化工具
   * @param time 时间戳传数字 new Date()格式传字符串
   * @param fmt
   * @returns {string}
   */
  dateFormat(time = 0, fmt = 'yyyy-MM-dd hh:mm:ss') {
    let date
    if (time === 0 || !time) {
      date = new Date()
    } else {
      date = new Date(time)
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    };
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        let str = o[k] + '';
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
      }
    }
    return fmt;
  },


  /***
   * 时间格式化工具
   * @param timestamp 时间戳传数字 new Date()格式传字符串
   * @return {string}
   */
  timeFormat(timestamp) {
    if (!timestamp) {
      return ''
    }
    if (typeof timestamp == 'string') {
      timestamp = new Date(timestamp).getTime();
    }
    // 补全为13位
    var arrTimestamp = (timestamp + '').split('');
    for (var start = 0; start < 13; start++) {
      if (!arrTimestamp[start]) {
        arrTimestamp[start] = '0';
      }
    }
    timestamp = arrTimestamp.join('') * 1;

    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - timestamp;

    // 如果本地时间反而小于变量时间
    if (diffValue < 0) {
      return '不久前';
    }

    // 计算差异时间的量级
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;

    // 数值补0方法
    var zero = function (value) {
      if (value < 10) {
        return '0' + value;
      }
      return value;
    };

    // 使用
    if (monthC > 12) {
      // 超过1年，直接显示年月日
      return (function () {
        var date = new Date(timestamp);
        return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) +
          '日';
      })();
    } else if (monthC >= 1) {
      return parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
      return parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
      return parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
      return parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
      return parseInt(minC) + "分钟前";
    }
    return '刚刚';
  },

  // 数字格式化工具
  numberFormat(num) {
    return num < 10000 ? num : (num / 10000).toFixed(1) + 'w'
  },


  // 错误团弹提示
  getAlert(tip) {
    tip = tip || '出错啦，请重试';
    uni.showToast({
      title: tip,
      duration: 2000,
      icon: 'none'
    })
  },


  // 给富文本框rich-text添加100%宽高
  formatRichText(html) {
    let newContent = html || ''
    if (newContent.indexOf("<img") >= 0) {
      newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        // match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        // match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
      });
      newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
        match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
        return match;
      });
      newContent = newContent.replace(/<br[^>]*\/>/gi, '');
      newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
    }
    return newContent;
  },

  // 给富文本框rich-text预览图片
  catchImage(e) {
    // 富文本点击事件
    // 富文本
    const richContent = e;
    // 判断含有图片
    if (richContent.indexOf("src") >= 0) {
      const imgs = [];
      richContent.replace(
        /]*src=['"]([^'"]+)[^>]*>/gi,
        function (match, capture) {
          imgs.push(capture);
        }
      );
      uni.previewImage({
        current: imgs[0], // 当前显示图片的链接
        urls: imgs,
      });
    }
  },

  // 跳转webview外链
  gotoWebview(data) {
    let open = encodeURIComponent(data)
    uni.navigateTo({
      url: `/pageContent/web/webview?url=${open}`,
    })
  },

  // 消息提示框
  showToast(data) {
    if (typeof data == 'string') {
      uni.showToast({
        title: data,
        duration: 2000,
        icon: 'none'
      });
      return
    }
    if (!data.title) {
      data.title = '操作成功'
    }
    if (!data.duration) {
      data.duration = '1500'
    }
    uni.showToast(data);
  },

  /* 获取随机整数 */
  randomNum(m, n) {
    var num = Math.floor(Math.random() * (m - n) + n);
    return num;
  },


  // 点击保存图片
  savePoster(url) {
    let fileName = new Date().valueOf();
    let filePath = wx.env.USER_DATA_PATH + "/" + fileName + ".jpg"; //这边就是为了安卓做的兼容，因为安卓机有可能会将图片地址的后缀名读取为：unknow
    wx.downloadFile({
      url: url, //需要保存的图片地址
      filePath: filePath,
      success: function (res) {
        // 保存图片到系统相册
        wx.saveImageToPhotosAlbum({
          filePath: filePath,
          success(data) {
            let fileMgr = wx.getFileSystemManager();
            fileMgr.unlink({
              filePath: filePath,
              success() {
                wx.showToast({
                  title: "已保存至您的相册",
                  icon: "none",
                  duration: 1500,
                });
              },
            });
          },
          fail(err) {
            if (
              err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" ||
              err.errMsg === "saveImageToPhotosAlbum:fail auth deny" ||
              err.errMsg ===
              "saveImageToPhotosAlbum:fail authorize no response"
            ) {
              wx.showModal({
                title: "提示",
                content: "需要您授权保存相册",
                showCancel: false,
                success: (modalSuccess) => {
                  wx.openSetting({
                    success(settingdata) {
                      if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                        console.log(
                          "获取权限成功，给出再次点击图片保存到相册的提示。"
                        );
                      } else {
                        console.log(
                          "获取权限失败，给出不给权限就无法正常使用的提示"
                        );
                      }
                    },
                  });
                },
              });
            }
          },
        });
      },
      fail: function (res) {},
    });
  },

}

export default utils